<template>
  <el-dialog
      :title="type == 'add' ? '添加药品信息' : '修改药品信息'"
      v-model="state.visible"
      width="800px"
  >
    <el-steps :active="state.activeStep" finish-status="success" simple>
      <el-step title="药品信息"></el-step>
      <el-step title="基本信息"></el-step>
      <el-step title="生产与定价"></el-step>
    </el-steps>

    <el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="120px" class="medicine-form">
      <!-- 药品信息 -->
      <el-row v-if="state.activeStep === 0">
        <el-col :span="12">
          <el-form-item label="药品图片" prop="medicineImg">
            <el-upload
                class="avatar-uploader"
                :action="state.uploadImgServer"
                accept="jpg,jpeg,png"
                :headers="{ 'hw-token': state.token }"
                :show-file-list="false"
                :before-upload="handleBeforeUpload"
                :on-success="handleUrlSuccess"
            >
              <img style="width: 200px; height: 100px; border: 1px solid #e9e9e9;" v-if="state.ruleForm.medicineImg"
                   :src="state.ruleForm.medicineImg" class="avatar">
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="药品名称" prop="medicineName">
            <el-input type="text" v-model="state.ruleForm.medicineName"></el-input>
          </el-form-item>
          <el-form-item label="药品描述" prop="description">
            <el-input type="text" v-model="state.ruleForm.description"></el-input>
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
            <el-cascader
                v-model="state.ruleForm.categoryId"
                :props="{ checkStrictly: true, emitPath: true, lazy: true, lazyLoad: loadCategories, value: 'categoryId', label: 'categoryName' }"
                placeholder="请选择分类"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="供应商" prop="supplierId">
            <el-select v-model="state.ruleForm.supplierId" placeholder="请选择供应商">
              <el-option
                  v-for="item in allSupplier"
                  :key="item.supplierId"
                  :label="item.supplierName"
                  :value="item.supplierId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="药店" prop="shopId">
            <el-select v-model="state.ruleForm.shopId" placeholder="请选择药店">
              <el-option
                  v-for="item in allShop"
                  :key="item.shopId"
                  :label="item.shopName"
                  :value="item.shopId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 基本信息 -->
      <el-row v-if="state.activeStep === 1">
        <el-col :span="12">
          <el-form-item label="主治功能" prop="func">
            <el-input type="text" v-model="state.ruleForm.func"></el-input>
          </el-form-item>
          <el-form-item label="用法用量" prop="useInstruction">
            <el-input type="text" v-model="state.ruleForm.useInstruction"></el-input>
          </el-form-item>
          <el-form-item label="不良反应" prop="adverseReactions">
            <el-input type="text" v-model="state.ruleForm.adverseReactions"></el-input>
          </el-form-item>
          <el-form-item label="禁忌" prop="taboo">
            <el-input type="text" v-model="state.ruleForm.taboo"></el-input>
          </el-form-item>
          <el-form-item label="药物相互作用" prop="interact">
            <el-input type="text" v-model="state.ruleForm.interact"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 生产与定价 -->
      <el-row v-if="state.activeStep === 2">
        <el-col :span="12">
          <el-form-item label="存储方式" prop="storage">
            <el-input type="text" v-model="state.ruleForm.storage"></el-input>
          </el-form-item>
          <el-form-item label="成分" prop="component">
            <el-input type="text" v-model="state.ruleForm.component"></el-input>
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input type="number" v-model="state.ruleForm.price"></el-input>
          </el-form-item>
          <el-form-item label="积分数" prop="point">
            <el-input type="number" v-model="state.ruleForm.point"></el-input>
          </el-form-item>
          <el-form-item label="库存" prop="stockQuantity">
            <el-input type="number" v-model="state.ruleForm.stockQuantity"></el-input>
          </el-form-item>
          <el-form-item label="生产日期" prop="manufactureDate">
            <el-date-picker v-model="state.ruleForm.manufactureDate" type="date"
                            placeholder="选择生产日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="过期时间" prop="expiryDate">
            <el-date-picker v-model="state.ruleForm.expiryDate" type="date" placeholder="选择过期时间"></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button v-if="state.activeStep > 0" @click="prevStep">上一步</el-button>
        <el-button v-if="state.activeStep < 2" @click="nextStep">下一步</el-button>
        <el-button type="primary" v-if="state.activeStep === 2" @click="submitForm">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue';
import {ElMessage} from 'element-plus';
import {createMedicine, updateMedicine, getMedicineDetail} from '@/api/drug';
import {getAllShop} from "@/api/shop";
import {getAllSupplier} from "@/api/supplier";
import {getAllFirstLevel, getChildrenDate, getChildrenDateTree} from '@/api/drugCategory'
import {localGet, ossPath, uploadImgServer} from '@/utils';

const props = defineProps({
  type: String,
  reload: Function
});

const formRef = ref(null);
const state = reactive({
  activeStep: 0, // 当前步骤
  visible: false,
  ruleForm: {
    medicineId: '',
    medicineName: '',
    description: '',
    func: '',
    useInstruction: '',
    adverseReactions: '',
    taboo: '',
    interact: '',
    storage: '',
    component: '',
    price: 0,
    point: 0,
    stockQuantity: 0,
    manufactureDate: '',
    expiryDate: '',
    supplierId: '',
    categoryId: '',
    shopId: '',
    medicineImg: '' // 修改为 medicineImg
  },
  rules: {
    medicineName: [
      {required: true, message: '请输入药品名称', trigger: 'blur'}
    ],
    description: [
      {required: true, message: '请输入药品描述', trigger: 'blur'}
    ],
    func: [
      {required: true, message: '请输入主治功能', trigger: 'blur'}
    ],
    useInstruction: [
      {required: true, message: '请输入用法用量', trigger: 'blur'}
    ],
    adverseReactions: [
      {required: true, message: '请输入不良反应', trigger: 'blur'}
    ],
    taboo: [
      {required: true, message: '请输入禁忌', trigger: 'blur'}
    ],
    medicineImg: [
      {required: true, message: '图片不能为空', trigger: 'change'}
    ]
  },
  categories: [],
  uploadImgServer: uploadImgServer, // 图片上传服务器地址
  token: localGet('token') || '' // 上传图片所需的token
});
const medicineIdInfo = ref(null);

// 动态加载分类
const loadCategories = async (node, resolve) => {
  const {level} = node;
  const parentId = level === 0 ? 0 : node.value;
  const res = await getChildrenDateTree({
    id: parentId
  });
  resolve(res.data.data);
};

const getDetail = async (medicineId) => {
  medicineIdInfo.value = medicineId;
  await getMedicineDetail(medicineId).then((res) => {
    state.ruleForm = res.data.data;
  });
};

// 开启弹窗
const open = (row) => {
  state.visible = true;
  getInformation();
  if (row) {
    getDetail(row.medicineId).then((res) => {
      state.ruleForm = res.data.data;
    })
  } else {
    state.ruleForm = {
      medicineId: '',
      medicineName: '',
      description: '',
      func: '',
      useInstruction: '',
      adverseReactions: '',
      taboo: '',
      storage: '',
      component: '',
      price: 0,
      medicineImg: '' // 修改为 medicineImg
    };
  }
};

// 关闭弹窗
const close = () => {
  state.visible = false;
  state.ruleForm = {};
  state.activeStep = 0;
};

// 下一步
const nextStep = () => {
  state.activeStep += 1;
};

// 上一步
const prevStep = () => {
  state.activeStep -= 1;
};

// 提交表单
const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.type == 'add') {
        if (state.ruleForm.categoryId.length != 3) {
          ElMessage.error('请选择正确的分类');
          return;
        }
        state.ruleForm.categoryId = state.ruleForm.categoryId[2];
        state.ruleForm.medicineId = null;
        await createMedicine(state.ruleForm).then(() => {
          ElMessage.success('添加成功');
          close();
          if (props.reload) props.reload();
        });
      } else {
        if (state.ruleForm.categoryId.length != 3) {
          ElMessage.error('请选择正确的分类');
          return;
        }
        state.ruleForm.categoryId = state.ruleForm.categoryId[2];
        // state.ruleForm.medicineId = null;

        console.log("修改id", state.ruleForm.medicineId)
        await updateMedicine(state.ruleForm).then(() => {
          ElMessage.success('修改成功');
          close();
          if (props.reload) props.reload();
        });
      }
    }
  });
};

const allShop = ref([]);
const allSupplier = ref([]);

// 获取选项信息
const getInformation = async () => {
  getAllShop().then((res) => {
    allShop.value = res.data.data;
  });
  getAllSupplier().then((res) => {
    allSupplier.value = res.data.data;
  });
};

// 上传图片前的验证
const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || '';
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片');
    return false;
  }
};

// 上传图片成功后的处理
const handleUrlSuccess = (val) => {
  state.ruleForm.medicineImg = ossPath + val.data || ''; // 修改为 medicineImg
};

defineExpose({open, close});
</script>


<style scoped>
.medicine-form {
  padding: 20px;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  color: #ddd;
  font-size: 30px;
}

.avatar-uploader >>> .el-upload {
  width: 100%;
  text-align: center;
}

.avatar-uploader-icon {
  display: block;
  width: 100%;
  height: 100%;
  border: 1px solid #e9e9e9;
  padding: 32px 17px;
}
</style>